/*
 * @Author: 
 * @Date: 2024-11-28 16:11:25
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-11-28 16:11:38
 * @Description: 
 */
import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { Subsystem } from '../entity/subsystem.entity';
import { Context } from '@midwayjs/koa';
import { CreateSubsystemDto, UpdateSubsystemDto } from '../dto/Subsystem.dto';

@Provide()
export class SubsystemService {
  @InjectEntityModel(Subsystem)
  SubsystemModel: Repository<Subsystem>;

  @Inject()
  ctx: Context;

  /**
   * 创建新子系统
   */
  async createSubsystem(createSubsystemDto: CreateSubsystemDto) {
    const { name, description } = createSubsystemDto;

    // 检查是否存在同名子系统
    const existingSubsystem = await this.SubsystemModel.findOne({ where: { name } });
    if (existingSubsystem) {
      return { success: false, message: '子系统名称已存在' };
    }

    const subsystem = this.SubsystemModel.create({ name, description });
    const savedSubsystem = await this.SubsystemModel.save(subsystem);

    return { success: true, data: savedSubsystem, message: '子系统创建成功' };
  }

  /**
   * 获取所有子系统
   */
  async getAllSubsystems() {
    const subsystems = await this.SubsystemModel.find();
    return { success: true, data: subsystems, message: '获取子系统列表成功' };
  }

  /**
   * 根据 ID 获取子系统
   */
  async getSubsystemById(id: string) {
    const subsystem = await this.SubsystemModel.findOne({ where: { id } });
    if (!subsystem) {
      return { success: false, message: '子系统未找到' };
    }
    return { success: true, data: subsystem, message: '获取子系统详情成功' };
  }

  /**
   * 更新子系统
   */
  async updateSubsystem(id: string, updateSubsystemDto: UpdateSubsystemDto) {
    const subsystem = await this.SubsystemModel.findOne({ where: { id } });
    if (!subsystem) {
      return { success: false, message: '子系统未找到' };
    }

    Object.assign(subsystem, updateSubsystemDto);
    const updatedSubsystem = await this.SubsystemModel.save(subsystem);

    return { success: true, data: updatedSubsystem, message: '子系统更新成功' };
  }

  /**
   * 删除子系统
   */
  async deleteSubsystem(id: string) {
    const subsystem = await this.SubsystemModel.findOne({ where: { id } });
    if (!subsystem) {
      return { success: false, message: '子系统未找到' };
    }

    await this.SubsystemModel.remove(subsystem);
    return { success: true, message: '子系统删除成功' };
  }
}
